package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teautil.models.RuntimeOptions;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exceptionhandler.BusiException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void getCode(String phone) {

        if (!StringUtils.hasText(phone)) {
            throw new BusiException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
//        todo 需要限制发短信的频率，如果redis中还存在之前发的验证码且存储的时间小于一分钟，就不能再发
//        超过一分钟，可以再发，会覆盖原验证码
        String redisCode = stringRedisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);

        if (redisCode != null) {
//            获取code剩余的有效时间
            Long expire = stringRedisTemplate.getExpire(RedisConstant.APP_LOGIN_PREFIX + phone, TimeUnit.SECONDS);
//            总的有效时间(存redis时设置的)减去剩余有效时间 = 过去了多长时间(已经存储的时间)
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                throw new BusiException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        String code = createCode(6);
//        专门发短信的工具方法，需传递往哪发，发什么
        sendCode(phone,code);

        stringRedisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX + phone, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);

    }

    @Override
    public String login(LoginVo loginVo) {

        String code = loginVo.getCode();
        String phone = loginVo.getPhone();

        if (code == null) {
            throw new BusiException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        if (phone == null) {
            throw new BusiException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        String redisCode = stringRedisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);
        if (redisCode == null) {
            throw new BusiException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        if (!redisCode.equals(code)){
            throw new BusiException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
//        todo 若账号不存在则注册
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setNickname("用户-" + phone.substring(phone.length()-7));
            userInfo.setPhone(phone);
            userInfo.setAvatarUrl("http://192.168.200.66:9000/lease/333d623f-e038-4f0f-b05d-f1f2d5c1f8cb2025-05-04-微信图片_20240527210214.jpg");
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo); //记得存库(隐式注册)
        }
        if(userInfo.getStatus() == BaseStatus.DISABLE){
            throw new BusiException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getNickname());

        return token;
    }

    public String createCode(Integer length) {
        StringBuffer code = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    public void sendCode(String phone,String code){

            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName("阿里云短信测试")
                    .setTemplateCode("SMS_154950909")
                    .setPhoneNumbers(phone)
                    .setTemplateParam("{\"code\":" + "\"" + code + "\"}");
            RuntimeOptions runtime = new RuntimeOptions();
            try {
                client.sendSmsWithOptions(sendSmsRequest, runtime);
            } catch (Exception error) {
               throw new BusiException(ResultCodeEnum.SERVICE_ERROR);
            }
        }


}
